#!/usr/bin/env python3
"""
数据库测试数据生成脚本
向数据库中插入20条测试数据，包括部门、用户、员工、项目和任务
"""
import os
import sys
from pathlib import Path
from sqlalchemy.orm import Session
import random
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.append(str(Path(__file__).parent.parent))

from app.core.database import SessionLocal, engine, Base
from app.models import user, department, employee, project, task
from app.services.auth_service import AuthService
from app.schemas.user import UserCreate
from app.schemas.department import DepartmentCreate

# 随机数据生成辅助函数
def generate_random_date(start_date, end_date):
    """生成指定范围内的随机日期"""
    delta = end_date - start_date
    random_days = random.randrange(delta.days)
    return start_date + timedelta(days=random_days)

# 样本数据
dept_names = ["技术部", "市场部", "人力资源部", "财务部", "销售部"]
dept_descriptions = [
    "负责公司产品的技术开发和维护",
    "负责市场推广和品牌建设",
    "负责人力资源管理和员工发展",
    "负责财务管理和报表分析",
    "负责产品销售和客户关系管理"
]

user_names = ["user001", "user002", "user003", "user004", "user005"]
user_full_names = ["李四", "王五", "赵六", "钱七", "孙八"]
user_emails = ["user001@example.com", "user002@example.com", "user003@example.com", "user004@example.com", "user005@example.com"]

employee_codes = ["EMP002", "EMP003", "EMP004", "EMP005", "EMP006"]
employee_full_names = ["周九", "吴十", "郑十一", "王十二", "陈十三"]
employee_emails = ["emp002@example.com", "emp003@example.com", "emp004@example.com", "emp005@example.com", "emp006@example.com"]
employee_positions = ["产品经理", "UI设计师", "前端开发", "后端开发", "测试工程师"]

project_names = ["客户管理系统", "数据分析平台", "营销自动化工具"]
project_descriptions = [
    "管理客户信息和互动记录的系统",
    "分析业务数据并生成可视化报表的平台",
    "自动化营销流程和客户沟通的工具"
]

task_titles = ["需求分析", "数据库设计"]
task_descriptions = [
    "分析用户需求并制定需求文档",
    "设计数据库结构和关系模型"
]

def create_test_data(db: Session):
    """创建测试数据"""
    print("🚀 开始生成测试数据...")
    created_count = 0
    
    # 1. 创建部门 (5条)
    departments = []
    for i in range(5):
        dept_data = DepartmentCreate(
            name=dept_names[i],
            description=dept_descriptions[i]
        )
        
        existing_dept = db.query(department.Department).filter(
            department.Department.name == dept_data.name
        ).first()
        
        if not existing_dept:
            new_dept = department.Department(**dept_data.dict())
            db.add(new_dept)
            departments.append(new_dept)
            print(f"✅ 创建部门 #{i+1}: {new_dept.name}")
            created_count += 1
        else:
            departments.append(existing_dept)
            print(f"⚠️ 部门 #{i+1} 已存在: {existing_dept.name}")
    
    db.commit()
    
    # 2. 创建用户 (5条)
    auth_service = AuthService(db)
    users = []
    
    # 获取admin用户用于项目创建
    admin_user = auth_service.get_user_by_username("admin")
    if admin_user:
        users.append(admin_user)
    
    for i in range(5):
        existing_user = auth_service.get_user_by_username(user_names[i])
        
        if not existing_user:
            user_data = UserCreate(
                username=user_names[i],
                email=user_emails[i],
                password="password123",  # 所有测试用户使用相同密码
                full_name=user_full_names[i],
                department_id=departments[i % len(departments)].id
            )
            new_user = auth_service.create_user(user_data)
            users.append(new_user)
            print(f"✅ 创建用户 #{i+1}: {new_user.username}")
            created_count += 1
        else:
            users.append(existing_user)
            print(f"⚠️ 用户 #{i+1} 已存在: {existing_user.username}")
    
    db.commit()
    
    # 3. 创建员工 (5条)
    employees = []
    start_date = datetime(2023, 1, 1).date()
    end_date = datetime(2024, 12, 31).date()
    
    for i in range(5):
        existing_emp = db.query(employee.Employee).filter(
            employee.Employee.employee_code == employee_codes[i]
        ).first()
        
        if not existing_emp:
            hire_date = generate_random_date(start_date, end_date)
            
            new_emp = employee.Employee(
                employee_code=employee_codes[i],
                full_name=employee_full_names[i],
                email=employee_emails[i],
                phone=f"1380013800{i+2}",
                position=employee_positions[i],
                department_id=departments[i % len(departments)].id,
                hire_date=hire_date,
                salary=10000.00 + i * 1000.00
            )
            db.add(new_emp)
            employees.append(new_emp)
            print(f"✅ 创建员工 #{i+1}: {new_emp.full_name}")
            created_count += 1
        else:
            employees.append(existing_emp)
            print(f"⚠️ 员工 #{i+1} 已存在: {existing_emp.full_name}")
    
    db.commit()
    
    # 4. 创建项目 (3条)
    projects = []
    project_start_date = datetime(2024, 1, 1).date()
    project_end_date = datetime(2025, 12, 31).date()
    
    for i in range(3):
        existing_project = db.query(project.Project).filter(
            project.Project.name == project_names[i]
        ).first()
        
        if not existing_project:
            proj_start = generate_random_date(project_start_date, project_end_date)
            proj_end = proj_start + timedelta(days=random.randint(30, 365))
            
            status_values = list(project.ProjectStatus)
            random_status = random.choice(status_values)
            
            new_project = project.Project(
                name=project_names[i],
                description=project_descriptions[i],
                status=random_status,
                start_date=proj_start,
                end_date=proj_end,
                budget=500000 + i * 200000,
                created_by=users[0].id  # 使用第一个用户作为创建者
            )
            db.add(new_project)
            projects.append(new_project)
            print(f"✅ 创建项目 #{i+1}: {new_project.name}")
            created_count += 1
        else:
            projects.append(existing_project)
            print(f"⚠️ 项目 #{i+1} 已存在: {existing_project.name}")
    
    db.commit()
    
    # 5. 创建任务 (2条)
    tasks = []
    task_due_date = datetime(2024, 12, 31).date()
    
    for i in range(2):
        existing_task = db.query(task.Task).filter(
            task.Task.title == task_titles[i],
            task.Task.project_id == projects[i].id
        ).first()
        
        if not existing_task:
            due_date = generate_random_date(project_start_date, task_due_date)
            
            status_values = list(task.TaskStatus)
            random_status = random.choice(status_values)
            
            priority_values = list(task.TaskPriority)
            random_priority = random.choice(priority_values)
            
            new_task = task.Task(
                title=task_titles[i],
                description=task_descriptions[i],
                status=random_status,
                priority=random_priority,
                due_date=due_date,
                project_id=projects[i].id,
                assigned_to=users[i+1].id if i+1 < len(users) else users[0].id
            )
            db.add(new_task)
            tasks.append(new_task)
            print(f"✅ 创建任务 #{i+1}: {new_task.title} (项目: {projects[i].name})")
            created_count += 1
        else:
            tasks.append(existing_task)
            print(f"⚠️ 任务 #{i+1} 已存在: {existing_task.title}")
    
    db.commit()
    
    print(f"🎉 测试数据生成完成！共创建 {created_count} 条新数据")


def main():
    """主函数"""
    print("🔧 开始生成数据库测试数据...")
    
    db = SessionLocal()
    try:
        create_test_data(db)
    except Exception as e:
        print(f"❌ 生成测试数据时出错: {e}")
        db.rollback()
        raise
    finally:
        db.close()


if __name__ == "__main__":
    main()